package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WechatServiceImpl implements IWechatService {

    @Value("${weChat.appId}")
    private String appid;
    @Value("${weChat.appSecret}")
    private String secret;
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Override
    public String getOpenid(String code) {
        Map paramMap = new HashMap<>();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");

        HttpResponse execute = HttpUtil.createRequest(Method.GET, OPENID_URL)
                .form(paramMap).execute();
        if (execute.isOk()){
            String body = execute.body();
           return body;
        }
        return null;
    }

    @Override
    public String getPhone(String phoneCode) {
        Map paramMap = new HashMap<>();

        paramMap.put("code",phoneCode);


        HttpResponse execute = HttpUtil.createRequest(Method.POST, PHONE_URL + token())
                .body(JSONUtil.toJsonStr(paramMap)).execute();
        if (execute.isOk()){
            String body = execute.body();
            JSONObject entries = JSONUtil.parseObj(body);
            String phoneNumber = entries.getByPath("phone_info.phoneNumber", String.class);
            return phoneNumber;
        }
        return null;
    }
    private String token(){
        Map paramMap = new HashMap<>();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        paramMap.put("grant_type","client_credential");

        HttpResponse execute = HttpUtil.createRequest(Method.GET, TOKEN_URL)
                .form(paramMap).execute();
        if (execute.isOk()){
            String body = execute.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            return jsonObject.getStr("access_token");
        }
        return null;
    }
}
